package osSRC.schedule;

import java.util.LinkedList;
import osSRC.Format;

class RoundRobinScheduler extends ProcessScheduler {
	static final int TITLE_LINE_NUM=3;
	String[] Titles=new String[TITLE_LINE_NUM];
	private static int round;
	//getters
	public static int getRound() {return round;}

	public RoundRobinScheduler(
			LinkedList<PCB> processSet,
			int timeSlice) {
		super(processSet);
		this.timeSlice=timeSlice;
		this.currentTime=0;
		round=1;
		this.Titles[0]=super.Titles[0]+"\tTime\tRounds";
		this.Titles[1]=super.Titles[1]+"\tSlices";
		this.Titles[2]=super.Titles[2]+"\tUsed";
	}
	// 时间片轮转调度算法
	@Override
	public void scheduling() {
		PCB current,last=null;
		while (true){
			System.out.println("Current Time:\t" + currentTime);
			for (String title:Titles) System.out.println(title);
			current=this.readyQueue.getFirst();
			if(last!=null)
				if(current.getPriority()<=last.getPriority())
					round++;
			for(PCB roundRobinPcb :readyQueue)
				System.out.println(roundRobinPcb);
			for (PCB roundRobinPcb :finishedQueue)
				System.out.println(roundRobinPcb);

			this.currentTime+=current.call(this.timeSlice);
			if(current.checkFinished())
				this.finishedQueue.add(current);
			else this.readyQueue.add(current);
			this.readyQueue.removeFirst();

			if(this.readyQueue.isEmpty()) {
				System.out.println("**ALL FINISHED**");
				System.out.println("Current Time:\t" + currentTime);
				for (String title:Titles) System.out.println(title);
				for (PCB pcb :finishedQueue){
					System.out.println(pcb);
				}
				Format.pause();
				break;
			}
			last=current;
		}
	}
}